import React, { useState, useEffect } from "react";
import routerArr from "../config/index";
import * as Icon from "@ant-design/icons";
import { Layout, Menu } from "antd";
import { useSelector, useDispatch } from "react-redux";
import { useNavigate, useLocation } from "react-router-dom";
import { selectMenuList } from "../store/reducers/tab";
const { Sider } = Layout;

const iconToElement = (name) => React.createElement(Icon[name]);

const menuArr = routerArr.map((item) => {
  const child = {
    key: item.path,
    icon: iconToElement(item.icon),
    label: item.label,
  };
  if (item.children && item.children.length) {
    child.children = item.children?.map((j) => ({
      key: j.path,
      icon: iconToElement(j.icon),
      label: j.label,
    }));
  }
  return child;
});

const Aside = () => {
  const { isCollapse } = useSelector((state) => state.tab);
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const location = useLocation();
  let [current, setCurrent] = useState(null);
  useEffect(() => {
    setCurrent(location.pathname);
    console.log(location);
  }, [location]);
  const selectMenu = (item) => {
    let data = null;
    routerArr.forEach((router) => {
      if (router.path === item.keyPath[item.keyPath.length - 1]) {
        data = router;
        if (item.keyPath.length > 1) {
          data = router.children.find((child) => {
            return child.path === item.key;
          });
        }
      }
    });
    dispatch(
      selectMenuList({
        path: data.path,
        name: data.name,
        label: data.label,
      })
    );
    navigate(item.key);
  };
  return (
    <Sider trigger={null} collapsible collapsed={isCollapse}>
      <div className="app-name">{isCollapse ? "后台" : "通用后台管理系统"}</div>
      <Menu
        style={{ height: "100%" }}
        theme="dark"
        mode="inline"
        defaultSelectedKeys={["/home"]}
        selectedKeys={[current]}
        items={menuArr}
        onClick={(item) => {
          selectMenu(item);
        }}
      />
    </Sider>
  );
};
export default Aside;
